import { NextRequest, NextResponse } from 'next/server';
import MonitoringManager from '@/services/blockchain/MonitoringManager';
import { PrismaClient } from '@prisma/client';
import { createModuleLogger } from '@/utils/logger';

const logger = createModuleLogger('status-api');

export async function GET(request: NextRequest) {
  try {
    // 获取监控管理器实例
    const monitoringManager = MonitoringManager.getInstance();
    const chainStatus = monitoringManager.getAllStatus();
    
    // 转换为monitor页面期望的格式
    const monitorStatusData: Record<string, any> = {};
    Object.entries(chainStatus).forEach(([chain, status]) => {
      monitorStatusData[chain] = {
        status: status.isActive ? 'running' : status.status,
        lastBlock: 0, // 可以后续从监控器获取实际区块号
        isActive: status.isActive,
        connections: status.isActive ? 1 : 0,
        lastActivity: status.lastActivity?.toISOString() || new Date().toISOString(),
        totalTransactions: status.totalTransactions,
        errorCount: status.errorCount
      };
    });

    // 获取数据库状态
    let recentAlerts = 0;
    let totalTransactions24h = 0;
    let largeTransactions24h = 0;
    
    try {
      const prisma = new PrismaClient();
      await prisma.$connect();
      
      const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000);
      
      // 并行查询数据库统计
      const [alerts, transactions24h, largeTransactions] = await Promise.all([
        prisma.alertMessage.count({
          where: {
            createdAt: { gte: yesterday }
          }
        }).catch(() => 0),
        
        prisma.transaction.count({
          where: {
            createdAt: { gte: yesterday }
          }
        }).catch(() => 0),
        
        prisma.transaction.count({
          where: {
            createdAt: { gte: yesterday },
            valueUsd: { gte: 10000 }
          }
        }).catch(() => 0)
      ]);
      
      recentAlerts = alerts;
      totalTransactions24h = transactions24h;
      largeTransactions24h = largeTransactions;
      
      await prisma.$disconnect();
      
    } catch (dbError) {
      logger.error('数据库连接失败:', dbError);
    }

    // 计算系统统计
    const activeChains = Object.values(chainStatus).filter(s => s.isActive).length;
    const totalMonitoredTransactions = Object.values(chainStatus).reduce((sum, s) => sum + s.totalTransactions, 0);

    return NextResponse.json({
      success: true,
      data: {
        server: {
          status: 'running',
          uptime: Math.floor(process.uptime()),
          memory: process.memoryUsage(),
          version: process.version,
          environment: process.env.NODE_ENV || 'development'
        },
        database: {
          status: 'connected',
          recentAlerts,
          totalTransactions24h,
          largeTransactions24h
        },
        blockchain: monitorStatusData,
        websocket: {
          status: 'active',
          connections: {
            total: Object.keys(chainStatus).length,
            active: activeChains,
            inactive: Object.keys(chainStatus).length - activeChains
          }
        },
        statistics: {
          activeChains,
          totalMonitoredTransactions,
          averageErrorRate: Object.values(chainStatus).reduce((sum, s) => sum + s.errorCount, 0) / Object.keys(chainStatus).length
        },
        timestamp: new Date().toISOString()
      }
    });

  } catch (error) {
    logger.error('Status API error:', error);
    return NextResponse.json({
      success: false,
      error: error instanceof Error ? error.message : 'Failed to get status',
      timestamp: new Date().toISOString()
    }, { status: 500 });
  }
} 